package com.gitee.wsl.platform

actual val platform:Platform = JavascriptPlatform

object JavascriptPlatform:Platform{
    override val current: PlatformType
        get() = platformType()

//    override val jsRuntime: JsRuntime
//        get() = getJsRuntime()

    override fun platformDisplay(chars: CharSequence){
        console.log(chars)
    }
}

fun isBrowser(): Boolean =
    js("""typeof window !== "undefined" && typeof window.document !== "undefined;" """) as Boolean

fun isNode(): Boolean =
    js("""typeof process !== "undefined" && process.versions != null && process.versions.node != null;""") as Boolean

internal fun platformType(): PlatformType = when {
    isBrowser() -> getBrowserPlatform()
    isNode() -> getNodePlatform()
    else -> getBrowserPlatform()
}

internal fun getNodePlatform(): PlatformType.JS.Node {
    val osName = eval("require('os').type()") as String
    val archName = eval("require('os').arch()") as String
    val osVersion = eval("require('os').version()") as String

    val os = when (osName) {
        "Windows" -> PlatformType.OS.Desktop.Windows(
            arch = Arch.fromString(archName),
            version = osVersion
        )
        "Linux" -> PlatformType.OS.Desktop.Linux(
            arch = Arch.fromString(archName),
            version = osVersion
        )
        "Darwin" -> PlatformType.OS.Desktop.MacOs(
            arch = Arch.fromString(archName),
            version = osVersion
        )

        else -> PlatformType.OS.Unknown( Arch.fromString(archName),osVersion)
    }

    return PlatformType.JS.Node(
        os = os,
        nodeVersion = eval("process.versions.node") as String,
        v8Version = eval("process.versions.v8") as String,
    )
}

fun getBrowserPlatform(): PlatformType.JS.Browser = PlatformType.JS.Browser(
    eval("navigator.userAgent") as String,
)